package com.ruoyi.project.system.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.project.system.mapper.SystemMapper;
import com.ruoyi.project.system.domain.dto.SystemDTO;
import com.ruoyi.project.system.domain.SystemEntity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 系统服务类（核心：查询身份证下所有预约记录，每条预约关联独立处方、药品）
 */
@Service
public class SystemService {
    private static final Logger log = LoggerFactory.getLogger(SystemService.class);

    @Autowired
    private SystemMapper systemMapper;

    // 常量定义
    private static final List<Integer> PROCESS_STATUS_TARGETS = Arrays.asList(1, 5); // 目标处理状态（有效预约）
    private static final Integer SUGGESTION_MODE_SELECT = 1; // 选择模式
    private static final Integer SUGGESTION_MODE_CUSTOM = 0; // 手写模式

    /**
     * 查询患者身份证下的所有有效预约记录（每条预约关联处方、建议、多药品）
     */
    @Transactional(readOnly = true)
    public SystemDTO.AllReservationsResponse queryAllReservations(String patientIdentityNumber) {
        SystemDTO.AllReservationsResponse result = new SystemDTO.AllReservationsResponse();
        List<SystemDTO.SingleReservationResponse> allReservations = new ArrayList<>();

        // 1. 查询该身份证下的所有有效预约记录（核心：不再取第一条，全部查询）
        List<SystemEntity> reservations = systemMapper.selectReservationByIdentityAndStatusIn(patientIdentityNumber, PROCESS_STATUS_TARGETS);
        if (reservations == null || reservations.isEmpty()) {
            log.warn("未查询到患者[{}]的有效预约记录（res_table：identity={}，resolve={}）",
                    patientIdentityNumber, patientIdentityNumber, PROCESS_STATUS_TARGETS);
            result.setReservationList(allReservations);
            result.setTotal(0);
            return result;
        }
        log.info("患者[{}]查询到{}条有效预约记录", patientIdentityNumber, reservations.size());

        // 2. 循环处理每条预约，分别查询关联的科室、处方、建议、药品
        for (SystemEntity reservation : reservations) {
            String reservationId = reservation.getReservationId();
            String departmentId = reservation.getDepartmentInformationId();

            // 2.1 查询当前预约的科室信息
            SystemEntity department = systemMapper.selectDepartmentById(departmentId);
            String departmentName = department != null ? department.getDepartmentName() : "未知科室";

            // 2.2 查询当前预约的处方+建议（取第一条，若需多条可扩展）
            SystemDTO.PrescriptionSuggestionResponse prescriptionSuggestion = buildPrescriptionSuggestion(reservationId);

            // 2.3 查询当前预约的多药品信息
            List<SystemDTO.MedicineDetailResponse> medicineList = buildMedicineList(reservationId);

            // 2.4 组装单条预约的完整信息
            SystemDTO.SingleReservationResponse singleResp = new SystemDTO.SingleReservationResponse();
            // 预约基础信息
            singleResp.setReservationId(reservationId);
            singleResp.setPatientName(reservation.getPatientName());
            singleResp.setPatientPhoneNumber(reservation.getPatientPhoneNumber());
            singleResp.setAttendingDoctorName(reservation.getAttendingDoctorName());
            singleResp.setPrescriptionCreateTime(reservation.getPrescriptionCreateTime());
            singleResp.setMedicineDistributionTime(reservation.getMedicineDistributionTime());
            singleResp.setDepartmentName(departmentName);
            // 关联信息
            singleResp.setPrescriptionSuggestion(prescriptionSuggestion);
            singleResp.setMedicineDetailList(medicineList);

            // 添加到总列表
            allReservations.add(singleResp);
        }

        // 3. 组装最终结果（总条数+所有预约列表）
        result.setReservationList(allReservations);
        result.setTotal(allReservations.size());
        return result;
    }

    /**
     * 构建单条预约的处方+建议（内部方法，支持多条处方取第一条）
     */
    private SystemDTO.PrescriptionSuggestionResponse buildPrescriptionSuggestion(String reservationId) {
        SystemDTO.PrescriptionSuggestionResponse response = new SystemDTO.PrescriptionSuggestionResponse();

        // 查询当前预约的所有处方（取第一条）
        List<SystemEntity> prescriptions = systemMapper.selectPrescriptionByReservationId(reservationId);
        if (prescriptions != null && !prescriptions.isEmpty()) {
            SystemEntity prescription = prescriptions.get(0);
            response.setPrescriptionId(prescription.getPrescriptionInformationId());
            response.setPatientSymptoms(prescription.getPatientSymptoms());
            response.setPrescriptionDescription(prescription.getPrescriptionDescription());
            log.info("预约[res_id={}]关联处方：{}条，取第1条（prescription_id={}）",
                    reservationId, prescriptions.size(), prescription.getPrescriptionInformationId());
        } else {
            response.setPatientSymptoms("无处方记录");
            response.setPrescriptionDescription("无");
            log.warn("预约[res_id={}]无关联处方", reservationId);
        }

        // 查询当前预约的所有建议（取第一条）
        List<SystemEntity> suggestions = systemMapper.selectSuggestionByReservationId(reservationId);
        if (suggestions != null && !suggestions.isEmpty()) {
            SystemEntity suggestion = suggestions.get(0);
            Integer mode = suggestion.getSuggestionInputMode();
            if (SUGGESTION_MODE_SELECT.equals(mode)) {
                response.setSportsSuggestion(suggestion.getSportsSuggestion());
                response.setDietSuggestion(suggestion.getDietSuggestion());
                response.setSleepSuggestion(suggestion.getSleepSuggestion());
            } else if (SUGGESTION_MODE_CUSTOM.equals(mode)) {
                response.setOtherCustomSuggestion(suggestion.getOtherCustomSuggestion());
            }
            log.info("预约[res_id={}]关联建议：{}条，取第1条（suggestion_id={}）",
                    reservationId, suggestions.size(), suggestion.getPersonalizedSuggestionId());
        } else {
            response.setSportsSuggestion("无建议记录");
            response.setDietSuggestion("无");
            response.setSleepSuggestion("无");
            log.warn("预约[res_id={}]无关联建议", reservationId);
        }

        return response;
    }

    /**
     * 构建单条预约的多药品列表（内部方法，支持多条药品）
     */
    private List<SystemDTO.MedicineDetailResponse> buildMedicineList(String reservationId) {
        List<SystemDTO.MedicineDetailResponse> medicineList = new ArrayList<>();

        // 查询当前预约的所有药品清单
        List<SystemEntity> personalMedicines = systemMapper.selectPersonalMedicineByReservationId(reservationId);
        if (personalMedicines == null || personalMedicines.isEmpty()) {
            log.warn("预约[res_id={}]无关联药品", reservationId);
            return medicineList;
        }

        // 循环组装每条药品信息
        for (SystemEntity pm : personalMedicines) {
            String medicineId = pm.getMedicineInformationId();
            SystemEntity medicine = systemMapper.selectMedicineById(medicineId);
            if (medicine == null) {
                log.warn("预约[res_id={}]关联的药品ID[{}]不存在（medicine_table）", reservationId, medicineId);
                continue;
            }

            SystemDTO.MedicineDetailResponse detail = new SystemDTO.MedicineDetailResponse();
            detail.setMedicineId(medicineId);
            detail.setMedicineName(medicine.getMedicineName());
            detail.setMedicinePrice(medicine.getMedicinePrice());
            detail.setMedicineSpecification(medicine.getMedicineSpecification());
            detail.setMedicineUsageMethod(medicine.getMedicineUsageMethod());
            detail.setMedicineQuantity(pm.getMedicineQuantity());
            medicineList.add(detail);
        }

        log.info("预约[res_id={}]关联药品：{}种", reservationId, medicineList.size());
        return medicineList;
    }
}